package com.farsunset.webhook.controller.hoxin;

import com.farsunset.webhook.model.HoxinEvent;
import com.farsunset.webhook.service.RobotChatService;
import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * 和信公众号webhook实现
 */
@RestController
public class HoxinAccountController {

	private static final String TEXT_BODY = "{\"code\":200,\"data\":{\"format\":0,\"content\":\"%s\"}}";

	@Resource
	private RobotChatService robotChatService;

	@PostMapping(value = "/hoxin/handle",produces = {MediaType.APPLICATION_JSON_VALUE})
	public String handle(@RequestBody HoxinEvent event) throws Exception {

		if (Objects.equals(event.action,HoxinEvent.ACTION_SUBSCRIBE)) {
			return doOnSubscribeEvent(event);
		}

		if (Objects.equals(event.action,HoxinEvent.ACTION_UNSUBSCRIBE)) {
			return doOnUnSubscribeEvent(event);
		}

		if (Objects.equals(event.action,HoxinEvent.ACTION_TEXT)) {
			return doOnReceivedTextEvent(event);
		}

		if (Objects.equals(event.action,HoxinEvent.ACTION_MENU)) {
			return doOnMenuEvent(event);
		}

		return "{\"code\":403,\"message\":\"未知的事件:" + event.action + "\"}";
	}

	private String doOnReceivedTextEvent(HoxinEvent event) throws Exception {

		String text = robotChatService.get(event.content,event.uid);

		if (text != null){

			return String.format(TEXT_BODY,text);
		}

		return IOUtils.toString(getClass().getResourceAsStream("/hoxin/response/text.txt"), StandardCharsets.UTF_8);
	}

	private String doOnMenuEvent(HoxinEvent event) throws IOException {
		if (event.content.equals("KEY_SUB_NEWS")) {
			return IOUtils.toString(getClass().getResourceAsStream("/hoxin/response/news.txt"),StandardCharsets.UTF_8);
		}
		if (event.content.equals("KEY_SUB_ARTICLE")) {
			return IOUtils.toString(getClass().getResourceAsStream("/hoxin/response/article.txt"),StandardCharsets.UTF_8);
		}
		return IOUtils.toString(getClass().getResourceAsStream("/hoxin/response/unknown_menu.txt"), StandardCharsets.UTF_8);
	}

	private String doOnSubscribeEvent(HoxinEvent event) {
		// TODO 处理取消订阅的逻辑
		return "{\"code\":200}";
	}

	private String doOnUnSubscribeEvent(HoxinEvent event) {
		// TODO 处理订阅的逻辑
		return "{\"code\":200}";
	}
}
